package com.ziq.zcamp.view.layoutmanager

import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter

class FilterAreaCategoryContentGridLayoutManager(context: Context?, spanCount: Int, val mAdapter:GroupedRecyclerViewAdapter?, val childSpanSize: ChildSpanSize?) : GridLayoutManager(context, spanCount) {

    interface ChildSpanSize {
        fun getChildSpanSize(groupPosition: Int, childPosition: Int): Int
    }

    init {
        setSpanSizeLookup()
    }


    private fun setSpanSizeLookup() {
        super.setSpanSizeLookup(object : SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                val count = spanCount
                if (mAdapter != null) {
                    val type: Int = mAdapter.judgeType(position)
                    //只对子项做Grid效果
                    if (type == GroupedRecyclerViewAdapter.TYPE_CHILD) {
                        val groupPosition: Int = mAdapter.getGroupPositionForPosition(position)
                        val childPosition: Int = mAdapter.getChildPositionForPosition(groupPosition, position)
                        return childSpanSize?.getChildSpanSize(groupPosition, childPosition)?:1
                    }
                }
                return count
            }
        })
    }

    override fun smoothScrollToPosition(
        recyclerView: RecyclerView?,
        state: RecyclerView.State?,
        position: Int
    ) {
        val scroller = object : LinearSmoothScroller(recyclerView!!.context) {
            override fun getVerticalSnapPreference(): Int {
                return SNAP_TO_START
            }
        }
        scroller.targetPosition = position
        startSmoothScroll(scroller)
    }

}